package com.lm.controller;

import com.lm.pojo.Lecture;
import com.lm.pojo.User;
import com.lm.pojo.UserInfo;
import com.lm.pojo.LoginUser;
import com.lm.result.MsgResult;
import com.lm.service.LectureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/lecture")
public class LectureController {

    @Autowired
    private LectureService lectureService;

    @GetMapping("/lecture")
    public String showLecturePage(Model model) {
        // 获取到了讲座时间字符串
        String lectureTimeStr = "2024-10-01 14:30";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        LocalDateTime lectureTime = LocalDateTime.parse(lectureTimeStr, formatter);
        model.addAttribute("lectureTime", lectureTime);
        return "page/lecture";
    }

    @GetMapping
    public String showLectures(Model model, 
                             @RequestParam(required = false) String category,
                             @RequestParam(required = false) String searchTitle) {
        List<Lecture> lectures;
        if (searchTitle != null && !searchTitle.trim().isEmpty()) {
            lectures = lectureService.searchLecturesByTitle(searchTitle);
        } else if (category != null && !category.isEmpty()) {
            lectures = lectureService.getLecturesByCategory(category);
        } else {
            lectures = lectureService.getAllLectures();
        }
        model.addAttribute("lectures", lectures);
        return "page/lecture";
    }

    @PostMapping("/add")
    public String addLecture(@RequestParam String title,
                           @RequestParam String category,
                           @RequestParam String time,
                           @RequestParam String location,
                           @RequestParam String description,
                           HttpSession session) {
        try {
            Lecture lecture = new Lecture();
            lecture.setTitle(title);
            lecture.setCategory(category);
            lecture.setLocation(location);
            lecture.setDescription(description);
            lecture.setAttendeeCount(0);
            
            // 从session中获取当前用户信息
            UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
            User loginUser = (User) session.getAttribute("loginUser");
            
            if (userInfo == null || loginUser == null) {
                return "redirect:/lecture?error=not_logged_in";
            }
            
            // 检查用户是否是专家或管理员
            if (loginUser.getRoleId() != 3 && loginUser.getRoleId() != 1) {
                return "redirect:/lecture?error=not_expert";
            }
            
            lecture.setNickname(userInfo.getNickname());
            lecture.setPublisherUid(loginUser.getUid());

            // 将字符串时间转换为Date对象
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
            Date date = sdf.parse(time);
            lecture.setTime(date);

            // 设置创建时间和更新时间
            Date now = new Date();
            lecture.setCreateTime(now);
            lecture.setUpdateTime(now);

            lectureService.addLecture(lecture);
            return "redirect:/lecture";
        } catch (ParseException e) {
            e.printStackTrace();
            return "redirect:/lecture?error=date_format";
        }
    }

    @PostMapping("/delete/{id}")
    @ResponseBody
    public String deleteLecture(@PathVariable Long id, HttpSession session) {
        try {
            User loginUser = (User) session.getAttribute("loginUser");
            if (loginUser == null) {
                return "请先登录";
            }
            
            // 获取讲座信息
            Lecture lecture = lectureService.getLectureById(id);
            if (lecture == null) {
                return "讲座不存在";
            }
            
            // 检查权限：管理员可以删除任何讲座，专家只能删除自己的讲座
            if (loginUser.getRoleId() != 1 && (loginUser.getRoleId() != 3 || !lecture.getPublisherUid().equals(loginUser.getUid()))) {
                return "无权限执行此操作";
            }
            
            lectureService.deleteLecture(id);
            return "success";
        } catch (RuntimeException e) {
            return e.getMessage();
        }
    }

    @PostMapping("/cancel/{id}")
    @ResponseBody
    public String cancelBooking(@PathVariable Long id, HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
        if (userInfo == null) {
            return "请先登录";
        }
        
        try {
            lectureService.cancelBooking(id, userInfo.getNickname());
            return "success";
        } catch (Exception e) {
            return "取消预约失败：" + e.getMessage();
        }
    }

    @PostMapping("/book/{id}")
    @ResponseBody
    public String bookLecture(@PathVariable Long id, HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
        if (userInfo == null) {
            return "请先登录";
        }
        try {
            lectureService.bookLecture(id, userInfo.getNickname());
            return "success";
        } catch (RuntimeException e) {
            return e.getMessage();
        }
    }

    // 查看讲座列表
    @GetMapping("/list")
    public String listLectures(Model model) {
        model.addAttribute("lectures", lectureService.getAllLectures());
        return "lecture/list";
    }

    // 查看单个讲座
    @GetMapping("/{id}")
    public String viewLecture(@PathVariable Long id, Model model) {
        model.addAttribute("lecture", lectureService.getLectureById(id));
        return "lecture/view";
    }

    // 发布讲座（专家和管理员可访问）
    @PreAuthorize("hasAnyRole('EXPERT', 'ADMIN')")
    @GetMapping("/publish")
    public String publishForm() {
        return "lecture/publish";
    }

    // 处理讲座发布
    @PreAuthorize("hasAnyRole('EXPERT', 'ADMIN')")
    @PostMapping("/publish")
    public String publishLecture(@ModelAttribute Lecture lecture, @AuthenticationPrincipal UserDetails userDetails) {
        User user = ((LoginUser) userDetails).getUser();
        lecture.setPublisherUid(user.getUid());
        lectureService.saveLecture(lecture);
        return "redirect:/lecture/list";
    }
}